package com.zy.mc_module.view;

import android.app.Activity;
import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatTextView;

/**
 * Created on 19/2/21
 * 自定义TextView 显示倒计时
 */
public class CountDownTextView extends AppCompatTextView {
    private CountDownTimer count;

    public CountDownTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CountDownTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /***
     * @param millisInFuture  总毫秒数
     * @param countDownInterval  倒计时间隔毫秒数
     * @param listener
     */
    public void setStart(Context context, long millisInFuture, long countDownInterval, OnCountDownListener listener) {
        if (millisInFuture == 0) {
            if (null != listener) {
                listener.onFinish();
            }
        } else {
            if (null != count) {
                count.cancel();
            }
            count = new CountDownTimer(millisInFuture, countDownInterval) {
                @Override
                public void onTick(long millisUntilFinished) {
                    Activity activity = (Activity) context;
                    if (activity.isFinishing()) {
                        count.cancel();
                    } else {
                        if (null != listener) {
                            listener.onTick(millisUntilFinished);
                        }
                    }
                }

                @Override
                public void onFinish() {
                    if (null != listener) {
                        listener.onFinish();
                    }
                }
            }.start();
        }
    }

    public void cancel() {
        if (null != count) {
            count.cancel();
        }
    }

    public interface OnCountDownListener {
        //倒计时中
        void onTick(long millisUntilFinished);

        //倒计时结束
        void onFinish();
    }
}
